package cn.rjzjh.tapestry.tams.pages.sys;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.commons.lang3.StringUtils;
import org.apache.tapestry5.annotations.Import;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.hibernate.annotations.CommitAfter;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.json.JSONArray;
import org.apache.tapestry5.util.TextStreamResponse;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.rjzjh.commons.util.assistbean.EasyUINode;
import cn.rjzjh.commons.util.web.EasyUiAssist;
import cn.rjzjh.commons.util.web.OperateResult;
import cn.rjzjh.tapestry.busi.SpringInit;
import cn.rjzjh.tapestry.busi.model.ca.CaResource;
import cn.rjzjh.tapestry.busi.model.ca.CaRole;
import cn.rjzjh.tapestry.busi.model.ca.CaRoleRes;
import cn.rjzjh.tapestry.busi.service.IMenuService;
import cn.rjzjh.tapestry.busi.service.IStaffService;
import cn.rjzjh.tapestry.busi.service.impl.CAServiceImpl;
import cn.rjzjh.tapestry.tams.base.ParentPage;
import cn.rjzjh.tapestry.tams.services.base.IHbService;

/****
 * 资源分派页面
 *
 * @author Administrator
 *
 */
@Import(stack = "easyuistack")
public class ResAllot extends ParentPage {
	public static Logger logger = LoggerFactory.getLogger(CAServiceImpl.class);

	@Inject
	private IHbService hbService;

	@Inject
	private IMenuService menuService;

	@Inject
	private IStaffService staffService;

	@Inject
	private Session session;

	@Property(write = false)
	private List<CaRole> roles;
	@Property
	private CaRole role;

	public String getTreeData() {
		List<EasyUINode> roots = menuService.findAllModuleMenu(I18NConvert,
				false);
		String retstr = EasyUiAssist.getTreeFromList(roots);
		return retstr;
	}

	public JSONArray onQuerySelResForRole(int roleid) {
		JSONArray retobj = new JSONArray();
		CaRole role = (CaRole) session.get(CaRole.class, roleid);
		if (CollectionUtils.isNotEmpty(role.getCaRoleReses())) {
			for (CaRoleRes roleRes : role.getCaRoleReses()) {
				retobj.put(roleRes.getCaResource().getId());
			}
		}
		return retobj;
	}

	@CommitAfter
	public TextStreamResponse onSaveMenuForRole() {
		String roleIdStr = request.getParameter("roleId");
		int roleid = Integer.parseInt(roleIdStr);
		String nodeIds = request.getParameter("nodeIds");
		// 删除所有关联的资源
		hbService.getQuery("delete CaRoleRes where caRole.id=?")
				.setInteger(0, roleid).executeUpdate();
		// 添加新的资源对象
		if (StringUtils.isNotBlank(nodeIds)) {
			CaRole role = (CaRole) session.get(CaRole.class, roleid);
			String[] resAry = nodeIds.split(",");
			for (String resIdStr : resAry) {
				int resid = Integer.parseInt(resIdStr);
				CaRoleRes insertObj = new CaRoleRes();
				insertObj.setAuthCode(1);
				insertObj.setCaRole(role);
				insertObj.setCaResource(new CaResource(resid));
				session.save(insertObj);
			}
		}
		return retSuccInfo();
	}

	@CommitAfter
	public TextStreamResponse onSaveRole() {
		String idstr = request.getParameter("id");
		String roleName = request.getParameter("roleName");
		String isValid = request.getParameter("isValid");
		String remark = request.getParameter("remark");
		CaRole caRole = new CaRole();
		if (StringUtils.isNotEmpty(idstr)) {
			caRole.setId(Integer.parseInt(idstr));
		}
		caRole.setRoleName(roleName);
		caRole.setIsValid(isValid);
		caRole.setRemark(remark);
		try {
			session.saveOrUpdate(caRole);
		} catch (Exception e) {
			logger.error("保存角色" + roleName + "出错", e);
			session.clear();
			return retErrorInfo("操作失败，请检查新加的角色是否已存在.");
		}
		return retSuccInfo();
	}

	@CommitAfter
	public TextStreamResponse onDelRole() {
		String idstr = request.getParameter("id");
		hbService.delById(CaRole.class, Integer.parseInt(idstr));
		return retSuccInfo();
	}

	@SetupRender
	void init() {
		roles = staffService.findValidRole();
		// 找到可以配置资源的角色,开发者角色拥有所有页面，不用配置
		final int devrole = Integer.parseInt(SpringInit.conf
				.getProperty("role.dev"));
		CollectionUtils.filter(roles, new Predicate() {
			@Override
			public boolean evaluate(Object object) {
				CaRole temp = (CaRole) object;
				return devrole != temp.getId();
			}
		});
	}
}
